package com.cxd.base.page.plugin;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;

import com.cxd.base.page.tag.TagPage;

/**
 * <一句话功能简述> <功能详细描述>
 * @author wtj
 * @date 2015年12月11日 下午8:20:32
 * @company CXD
 * @version [Copyright (c) 2015 V001]
 */
public class PagePluginUtil {
	static void init(Invocation ivk, MappedStatement mappedStatement,BaseStatementHandler delegate,String dialect) throws Throwable{
        BoundSql boundSql = delegate.getBoundSql();
        Object parameterObject = boundSql.getParameterObject();
        if (parameterObject == null) {
            throw new NullPointerException("parameterObject error");
        } else {
            Connection connection = (Connection) ivk.getArgs()[0];
            String sql = boundSql.getSql();
            String countSql = "select count(0) from (" + sql + ") myCount";
//            System.out.println("总数sql 语句:"+countSql);
            PreparedStatement countStmt = connection
                    .prepareStatement(countSql);
            BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql,boundSql.getParameterMappings(), parameterObject);
            setParameters(countStmt, mappedStatement, countBS,parameterObject);
            ResultSet rs = countStmt.executeQuery();
            int count = 0;
            if (rs.next()) {
                count = rs.getInt(1);
            }
            rs.close();
            countStmt.close();

            TagPage page = null;
            if (parameterObject instanceof TagPage) {
                page = (TagPage) parameterObject;
                page.setTotalResult(count);
            } else if(parameterObject instanceof Map){
                Map<String, Object> map = (Map<String, Object>)parameterObject;
                if(((Map<String,Object>)map.get("root")).get("page")!=null){
                	page = (TagPage)((Map<String,Object>)map.get("root")).get("page");
                }else{
                	page = (TagPage)map.get("page");
                }
                
                if(page == null)
                    page = new TagPage();
                page.setTotalResult(count);
            }else {
                Field pageField = ReflectHelper.getFieldByFieldName(
                        parameterObject, "page");
                if (pageField != null) {
                    page = (TagPage) ReflectHelper.getValueByFieldName(
                            parameterObject, "page");
                    if (page == null)
                        page = new TagPage();
                    page.setTotalResult(count);
                    ReflectHelper.setValueByFieldName(parameterObject,
                            "page", page);
                } else {
                    throw new NoSuchFieldException(parameterObject
                            .getClass().getName());
                }
            }
            String pageSql = generatePageSql(sql, page,dialect);
//            System.out.println("page sql:"+pageSql);
            ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql);
        }
	};
	
    @SuppressWarnings("unchecked")
	static void setParameters(PreparedStatement ps,
            MappedStatement mappedStatement, BoundSql boundSql,
            Object parameterObject) throws SQLException {
        ErrorContext.instance().activity("setting parameters")
                .object(mappedStatement.getParameterMap().getId());
        List<ParameterMapping> parameterMappings = boundSql
                .getParameterMappings();
        if (parameterMappings != null) {
            Configuration configuration = mappedStatement.getConfiguration();
            TypeHandlerRegistry typeHandlerRegistry = configuration
                    .getTypeHandlerRegistry();
            MetaObject metaObject = parameterObject == null ? null
                    : configuration.newMetaObject(parameterObject);
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping parameterMapping = parameterMappings.get(i);
                if (parameterMapping.getMode() != ParameterMode.OUT) {
                    Object value;
                    String propertyName = parameterMapping.getProperty();
                    PropertyTokenizer prop = new PropertyTokenizer(propertyName);
                    if (parameterObject == null) {
                        value = null;
                    } else if (typeHandlerRegistry
                            .hasTypeHandler(parameterObject.getClass())) {
                        value = parameterObject;
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        value = boundSql.getAdditionalParameter(propertyName);
                    } else if (propertyName
                            .startsWith(ForEachSqlNode.ITEM_PREFIX)
                            && boundSql.hasAdditionalParameter(prop.getName())) {
                        value = boundSql.getAdditionalParameter(prop.getName());
                        if (value != null) {
                            value = configuration.newMetaObject(value)
                                    .getValue(
                                            propertyName.substring(prop
                                                    .getName().length()));
                        }
                    } else {
                        value = metaObject == null ? null : metaObject
                                .getValue(propertyName);
                    }
                    @SuppressWarnings("rawtypes")
					TypeHandler typeHandler = parameterMapping.getTypeHandler();
                    if (typeHandler == null) {
                        throw new ExecutorException(
                                "There was no TypeHandler found for parameter "
                                        + propertyName + " of statement "
                                        + mappedStatement.getId());
                    }
                    typeHandler.setParameter(ps, i + 1, value,
                            parameterMapping.getJdbcType());
                }
            }
        }
    }
    
    static String generatePageSql(String sql, TagPage page,String dialect) {
        if (page != null && (dialect !=null || !dialect.equals(""))) {
            StringBuffer pageSql = new StringBuffer();
            if ("mysql".equals(dialect)) {
                pageSql.append(sql);
                pageSql.append(" limit " + page.getCurrentResult() + ","
                        + page.getShowCount());
            } else if ("oracle".equals(dialect)) {
                pageSql.append("select * from (select tmp_tb.*,ROWNUM row_id from (");
                pageSql.append(sql);
                pageSql.append(")  tmp_tb where ROWNUM<=");
                pageSql.append(page.getCurrentResult() + page.getShowCount());
                pageSql.append(") where row_id>");
                pageSql.append(page.getCurrentResult());
            }
            return pageSql.toString();
        } else {
            return sql;
        }
    }
}
